package com.sunzm.flink.datastream.java;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * 从sockert中获取数据，计算wordcount - java 版
 *
 * @author Administrator
 * @version 1.0
 * @date 2021-06-16 16:56
 */
public class SocketSourceJava {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStream<Tuple2<String, Integer>> dataStream = env
                .socketTextStream("82.156.210.70", 9999)
                .flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {

                    @Override
                    public void flatMap(String line, Collector<Tuple2<String, Integer>> out) throws Exception {
                        for (String word : line.split(",")) {
                            out.collect(new Tuple2<String, Integer>(word, 1));
                        }
                    }

                })
                //.keyBy(value -> value.f0)
                .keyBy(new KeySelector<Tuple2<String, Integer>, String>() {

                    @Override
                    public String getKey(Tuple2<String, Integer> value) throws Exception {
                        return value.f0;
                    }

                })
                .sum(1);

        dataStream.print();

        //启动程序
        String className = Thread.currentThread().getStackTrace()[1].getClassName();
        String simpleName = className.substring(className.lastIndexOf(".") + 1);
        env.execute(simpleName);
    }
}
